package com.sencorsta.ids.common.service;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sencorsta.ids.core.configure.SysConfig;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.utils.string.StringUtil;

import java.util.Map;

/**
* @description: 极光推送
* @author TAO
* @date 2019/8/6 22:45
*/
public class AuroraPush implements RedisService {

    public static void pushAurora(String msgId){

        Out.debug("---------------------------极光推送的方法-------------------");

        //通过消息Id得到消息详情
        JSONObject msgInfo=JSONObject.parseObject(R_MESSAGES.get(msgId));

        if (msgInfo==null) {
            return;
        }


        //得到消息的属性值
        int tagType=msgInfo.getInteger("tagType");//接收方类型  1.个人  2.群
        int msgType=msgInfo.getInteger("msgType");//消息类型
        String msgContent=msgInfo.getString("msgContent");//消息内容
        String srcId=msgInfo.getString("srcId");//发送方Id
        String tagId=msgInfo.getString("tagId");//目标Id


        //TODO 这里对msgType为图片、表情做判断

        //消息类型 0系统消息 1图文，2图片，3.表情 4 文件 5 语音 6 视频
        //消息类型 0系统消息 1图文，2图片，3.表情 4 文件 5 语音 6 视频 7 红包 8 转账
        switch (msgType){

            case 2:
                msgContent="[ 图片 ]";
                break;
            case 3:
                msgContent="[ 表情 ]";
                break;
            case 4:
                msgContent="[ 文件 ]";
                break;
            case 5:
                msgContent="[ 语音 ]";
                break;
            case 6:
                msgContent="[ 视频 ]";
                break;
            case 7:
                msgContent="[ 红包 ]";
                break;
            case 8:
                msgContent="[ 转账 ]";
                break;
        }

        //TODO 极光推送字节数控制  4000
        if (msgContent.length()>18){
            msgContent=msgContent.substring(0,17)+"...";
        }

        //TODO 这里对srcId为系统消息做判断

       String name="";

        if ("0".equals(srcId)){
            name="系统";
        }else{
                name= R_USER.hget(srcId,"nickname");
        }


        if (tagType==1){//个人
            Out.debug("--------------------极光推个人-------------------");

            //得到个人的推送状态
            String registrationId=tagId;

            Out.debug("极光推送的当前用户Id为"+tagId+"推送条件如下-------------------↓↓↓↓↓↓↓");
            Out.debug("registrationId----------"+registrationId);

            AuroraPush.pushAlert(name,msgContent,registrationId);

        }else{//群

            Out.debug("--------------------极光推群-------------------");

            //通过tagId得到群的成员列表

            Map<String, String> memberList= R_GROUP.hgetAll(tagId);

            //得到群name

            String groupName=R_PROPERTY.hget(tagId,"groupName");

            String finalMsgContent = msgContent;
            String finalName = name;
            memberList.keySet().forEach(key->{

                Out.debug("群成员Id-----------"+key);
                Out.debug("srcId-----------"+srcId);

                if (!key.equals(srcId)){
                    AuroraPush.pushAlert(groupName, finalName +":"+finalMsgContent,key);
                }
            });
        }
    }

    public static void pushAlert(String title,String msgContent,String registration_id){
            Out.debug("当前推的registration_id------------------"+registration_id);

            JPushClient jpushClient = new JPushClient(SysConfig.getInstance().get("master.secret"), SysConfig.getInstance().get("app.key"), null, ClientConfig.getInstance());

            String osCode=R_USER.hget(registration_id,"osCode");

            Out.debug("osCode--------------"+osCode);

            try {

                PushResult result;
                if ("0".equals(osCode)) {//安装机型
                    if (StringUtil.isNotEmpty(title)) {

                    }

                    PushPayload payload = PushPayload.newBuilder()
                            .setPlatform(Platform.android())
                            .setAudience(Audience.alias(registration_id))
                            .setNotification(Notification.android(msgContent, title, null))
                            .build();

                    result=jpushClient.sendPush(payload);

                    Out.debug("安卓 result - " + result);
                } else if ("1".equals(osCode)) {//IOS机型


                    JsonObject content = new JsonObject();
                    content.addProperty("title", title);
                    //content.addProperty("subtitle", subTitle);
                    content.addProperty("body", msgContent);

                    Out.debug("--------------content-------------"+content);

                    PushPayload payload = PushPayload.newBuilder()
                            .setPlatform(Platform.ios())
                            .setAudience(Audience.alias(registration_id))
                            .setNotification(Notification.newBuilder()
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setAlert(content)
                                            .setSound("happy")
                                            .addExtra("from", "JPush").build())
                                    .build())
                            .build();

                    result = jpushClient.sendPush(payload);

                    Out.debug("IOS result - " + result);
                } else {
                    Out.debug("osCode未知,停止推送");
                }


            } catch (APIConnectionException e) {
                Out.error("Connection error, should retry later", e);
            } catch (APIRequestException e) {
                Out.info("Error Message: " + e.getErrorMessage());
            }catch (Error e){
                Out.info("Error Message: ");
            }
    }



}
